import re

def write_configure(typ, hst):
    """
    修改velocity.toml文件中的服务器配置。

    参数:
        typ (str): 要修改的服务器类型，可以是'server'或'slimefun'。
        hst (str): 新的主机地址，格式为'ip:port'。
    """
    # 读取原始配置文件内容
    try:
        with open('velocity.toml', 'r', encoding='utf-8') as file:
            lines = file.readlines()
    except FileNotFoundError:
        print("配置文件velocity.toml未找到。")
        return

    # 定义要修改的正则表达式模式
    server_pattern = re.compile(r'^\s*server\s*=\s*"[^"]+"')
    slimefun_pattern = re.compile(r'^\s*slimefun\s*=\s*"[^"]+"')
    forced_host_start_pattern = re.compile(r'^\s*\[forced-hosts\]\s*')
    forced_host_end_pattern = re.compile(r'^\s*# force host write point ending\s*')

    # 标记是否在[servers]和[forced-hosts]之间
    in_servers_section = False
    in_forced_hosts_section = False

    # 修改配置内容
    new_lines = []
    i = 0
    while i < len(lines):
        line = lines[i]

        # 检查是否进入[servers]部分
        if line.strip() == '[servers]':
            in_servers_section = True
        # 检查是否离开[servers]部分
        elif line.strip().startswith('[') and line.strip() != '[servers]':
            in_servers_section = False

        # 检查是否进入[forced-hosts]部分
        if forced_host_start_pattern.match(line):
            in_forced_hosts_section = True
            new_lines.append(line)  # 添加[forced-hosts]部分的标题
            i += 1
            continue
        # 检查是否离开[forced-hosts]部分
        elif forced_host_end_pattern.match(line):
            in_forced_hosts_section = False
            new_lines.append(line)  # 添加结束标记
            i += 1
            continue

        # 在[servers]部分进行修改
        if in_servers_section:
            if typ == 'server' and server_pattern.match(line):
                new_lines.append(f'server = "{hst}"\n')
            elif typ == 'slimefun' and slimefun_pattern.match(line):
                new_lines.append(f'slimefun = "{hst}"\n')
            else:
                new_lines.append(line)
        # 在[forced-hosts]部分进行修改
        elif in_forced_hosts_section:
            # 检查是否需要删除的条目
            if line.strip().startswith('"') and line.strip().endswith(']') and f'"{typ}"' in line:
                # 删除这一行
                i += 1
                continue
            new_lines.append(line)
        else:
            new_lines.append(line)
        i += 1

    # 添加新的[forced-hosts]条目
    if typ == 'server':
        # 添加到[forced-hosts]部分的第一行
        for i, line in enumerate(new_lines):
            if line.strip() == '[forced-hosts]':
                new_lines.insert(i + 1, f'"{hst}" = ["server"]\n')
                break
    elif typ == 'slimefun':
        # 添加到# force host write point ending前面的一行
        for i, line in enumerate(new_lines):
            if forced_host_end_pattern.match(line):
                new_lines.insert(i, f'"{hst}" = ["slimefun"]\n')
                break

    # 将修改后的内容写回文件
    try:
        with open('velocity.toml', 'w', encoding='utf-8') as file:
            file.writelines(new_lines)
        print(f"配置文件已更新：{typ} -> {hst}")
    except Exception as e:
        print(f"写入配置文件时出错：{e}")
